import 'package:flutter/material.dart';

typedef OnItemDispose = Function(GlobalKey<AnimeWrapperState> key);

class AnimeWrapper extends StatefulWidget {
  final Widget child;
  final int index;
  final OnItemDispose onItemDispose;
  final GlobalKey<AnimeWrapperState> itemKey;

  const AnimeWrapper({
    required this.itemKey,
    required this.child,
    required this.index,
    required this.onItemDispose,
  }) : super(key: itemKey);

  @override
  State<AnimeWrapper> createState() => AnimeWrapperState();
}

class AnimeWrapperState extends State<AnimeWrapper> with TickerProviderStateMixin {
  double _opacity = 1;

  final GlobalKey _childKey = GlobalKey();

  double _animeHeight = 1500;

  @override
  void initState() {
    // debugPrint("init ${widget.index}");
    // debugPrint("screenWidth = $screenWidth, screenHeight = $screenHeight");
    WidgetsBinding.instance.addPostFrameCallback((callBack) {
      // 获取控件宽高
      // double childWidth = _childKey.currentContext?.size?.width ?? 0;
      double childHeight = _childKey.currentContext?.size?.height ?? 0;
      _animeHeight = childHeight;
      _refresh();
      // debugPrint("childWidth = $childWidth, childHeight = $childHeight");
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Container(
        constraints: BoxConstraints(maxHeight: _animeHeight),
        child: Opacity(
          opacity: _opacity,
          child: Container(
            child: widget.child,
            key: _childKey,
          ),
        ),
      ),
      onTap: () {},
    );
  }

  @override
  void dispose() {
    // debugPrint("dispose ${widget.index}");
    widget.onItemDispose.call(widget.itemKey);
    super.dispose();
  }

  late AnimationController _animationController;
  late Animation<double> _animation;

  void startRemoveAnime() {
    _animationController = AnimationController(vsync: this, duration: const Duration(seconds: 1));
    _animation = Tween(begin: 1.0, end: 0.0).animate(_animationController)
      ..addListener(() {
        _opacity = _animation.value;
        _animeHeight *= _animation.value;
        _refresh();
      })
      ..addStatusListener((status) {
        if (AnimationStatus.completed == status) {}
      });
    _animationController.forward();
  }

  _refresh() {
    if (mounted) setState(() {});
  }
}
